package com.handyshop.mall.user.provider;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.handyshop.mall.basic.core.constants.BaseConstants;
import com.handyshop.mall.basic.core.constants.BaseRedisKey;
import com.handyshop.mall.dubbo.user.api.ISysUserDubboService;
import com.handyshop.mall.dubbo.user.dto.user.UserVo;
import com.handyshop.mall.dubbo.user.entity.SysMenu;
import com.handyshop.mall.dubbo.user.entity.SysOrg;
import com.handyshop.mall.dubbo.user.entity.SysRole;
import com.handyshop.mall.dubbo.user.entity.SysUser;
import com.handyshop.mall.user.service.SysMenuService;
import com.handyshop.mall.user.service.SysOrgService;
import com.handyshop.mall.user.service.SysRoleService;
import com.handyshop.mall.user.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.cache.annotation.Cacheable;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hs
 * @date 2020-12-01 18:25
 **/
@DubboService
@RequiredArgsConstructor
public class SysUserDubboServiceImpl implements ISysUserDubboService {
    private final SysUserService sysUserService;
    private final SysRoleService sysRoleService;
    private final SysMenuService sysMenuService;
    private final SysOrgService sysOrgService;

    /**
     * 根据用户名查询用户信息
     *
     * @param name 用户名
     * @return 用户信息
     */
    @Override
    @Cacheable(value = BaseRedisKey.USER_DETAILS, key = "#name", unless = "#result == null")
    public UserVo findByName(String name) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, name).eq(SysUser::getDeleteFlag, BaseConstants.NOT_DELETE_FLAG);
        SysUser sysUser = sysUserService.getOne(wrapper);
        if (sysUser == null) {
            return null;
        }

        UserVo userVo = BeanUtil.copyProperties(sysUser, UserVo.class);

        // 获取角色
        List<SysRole> sysRoles = sysRoleService.findByUserId(userVo.getId());
        if (CollUtil.isNotEmpty(sysRoles)) {
            userVo.setSysRoles(sysRoles);
            // 获取菜单
            List<SysMenu> sysMenus = sysMenuService.findMenuByRoleIds(sysRoles.stream().map(SysRole::getId).collect(Collectors.toList()));
            userVo.setSysMenus(sysMenus);
        }
        // 获取部门
        List<SysOrg> sysOrgs = sysOrgService.findByUserId(userVo.getId());
        userVo.setSysOrgs(sysOrgs);
        return userVo;
    }

}
